package com.w3c.pragmatic.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis配置类
 *
 * @author wangdong
 * @since 2025/3/6 10:59
 */
@Slf4j
@Configuration
public class RedisConfig {

  @Value("${spring.redis.host}")
  private String redisHost;

  @Value("${spring.redis.port}")
  private int redisPort;

  @Value("${spring.redis.database}")
  private int redisDatabase;

  @Value("${spring.redis.password}")
  private String redisPassword;

  // 配置redis连接对象
  @Bean
  public RedisConnectionFactory redisConnectionFactory() {
    // 配置redis连接
    RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(redisHost, redisPort);
    config.setDatabase(redisDatabase);
    config.setPassword(redisPassword);
    // 配置连接池
    GenericObjectPoolConfig<Object> poolConfig = new GenericObjectPoolConfig<>();
    poolConfig.setMaxTotal(10); // 连接池中的最大连接数
    poolConfig.setMaxIdle(5); // 连接池中的最大空闲连接数
    poolConfig.setMinIdle(1); // 连接池中的最小空闲连接数
    // 创建一个带有连接池配置的 Lettuce 客户端配置
    LettucePoolingClientConfiguration clientConfig =
        LettucePoolingClientConfiguration.builder().poolConfig(poolConfig).build();
    // 返回配置
    return new LettuceConnectionFactory(config, clientConfig);
  }

  // 初始化连接redis
  @Bean
  public RedisTemplate<String, Object> redisTemplate() {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(redisConnectionFactory());
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    log.info("redis connection success. db = {}", template);
    return template;
  }
}
